package com.example.tabbar.utils

import android.content.Context
import android.provider.Settings
import android.view.Window
import kotlin.math.max
import kotlin.math.min


class BrightnessUtils {
    // 检查是否有修改系统设置的权限
    fun hasWriteSettingsPermission(context: Context?): Boolean {
        return Settings.System.canWrite(context)
    }

    // 获取当前系统亮度
    fun getSystemBrightness(context: Context): Int {
        try {
            return Settings.System.getInt(
                context.contentResolver,
                Settings.System.SCREEN_BRIGHTNESS
            )
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
            return 100 // 默认值
        }
    }

    // 设置系统亮度（需要WRITE_SETTINGS权限）
    fun setSystemBrightness(context: Context, brightness: Int) {
        // 亮度值范围：0-255
        var brightness = brightness
        brightness = max(0.0, min(255.0, brightness.toDouble())).toInt()

        val contentResolver = context.contentResolver
        Settings.System.putInt(
            contentResolver,
            Settings.System.SCREEN_BRIGHTNESS,
            brightness
        )
    }
    fun setAppBrightness(window: Window, brightness: Float) {
        // 亮度值范围：0.0-1.0
        var brightness = brightness
        brightness = max(0.0, min(1.0, brightness.toDouble())).toFloat()

        val layoutParams = window.attributes
        layoutParams.screenBrightness = brightness
        window.attributes = layoutParams
    }

    // 将百分比转换为系统亮度值（0-255）
    fun percentageToSystemValue(percentage: Int): Int {
        return (percentage * 2.55).toInt() // 255 * percentage / 100
    }

    fun systemValueToPercentage(systemValue: Int): Int {
        return (systemValue / 255.0 * 100).toInt()
    }
}